package Servlet.Student;

import Entity.Grade.Score;
import Entity.Role.Student;

import Service.Student.HomeService;
import Service.Student.Imp.HomeServiceImp;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.SneakyThrows;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet(urlPatterns = {"/getStuInfo", "/getStuScore"})
public class HomeServlet extends HttpServlet {
    @SneakyThrows
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String url = request.getRequestURI();
        if ("/getStuInfo".equals(url)) {
            getStuInfo(request, response);
        } else if ("/getStuScore".equals(url)) {
            getStuScore(request, response);
        }
    }


    /**
     * 获取评分信息
     */
    private void getStuScore(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        HomeService homeServiceImp = new HomeServiceImp();
        String sno = request.getParameter("sno");
        List<Score> stuScore = homeServiceImp.getStuScore(sno);
        String json = JSONObject.toJSONString(stuScore, SerializerFeature.WriteMapNullValue);
        PrintWriter out = response.getWriter();
        out.print(json);
        out.close();

    }

    /**
     * 获取学生信息
     */
    private void getStuInfo(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        HomeService homeService = new HomeServiceImp();
        String sno = request.getParameter("sno");
        Student stuInfo = homeService.getStuInfo(sno);
        String json = JSONObject.toJSONString(stuInfo, SerializerFeature.WriteMapNullValue);
        PrintWriter out = response.getWriter();
        out.print(json);
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
